// pages/travel/create/index.ts
import { travelApi } from '../../../utils/api';
import { requireAuth } from '../../../utils/auth';

Page({
  data: {
    formData: {
      title: '',
      description: '',
      location: '',
      latitude: null as number | null,
      longitude: null as number | null,
      start_date: '',
      end_date: '',
      images: [] as string[],
    },
    loading: false,
  },

  onLoad() {
    const today = this.formatDate(new Date());
    this.setData({
      'formData.start_date': today,
      'formData.end_date': today,
    });
  },

  formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 输入框变化处理
  onInputChange(e: any) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    this.setData({
      [`formData.${field}`]: value,
    });
  },

  // 选择开始日期
  onStartDateChange(e: any) {
    this.setData({
      'formData.start_date': e.detail.value,
    });
  },

  // 选择结束日期
  onEndDateChange(e: any) {
    this.setData({
      'formData.end_date': e.detail.value,
    });
  },

  // 选择位置
  async onChooseLocation() {
    try {
      const res = await wx.chooseLocation({});
      if (res && res.name && res.latitude && res.longitude) {
        this.setData({
          'formData.location': res.name,
          'formData.latitude': res.latitude,
          'formData.longitude': res.longitude,
        });
      } else {
        // 用户可能取消了选择或者选择无效
        console.log('位置选择取消或无效');
      }
    } catch (error) {
      console.error('选择位置失败:', error);
      wx.showToast({
        title: '选择位置失败',
        icon: 'none',
      });
    }
  },


  // 选择图片（本地预览）
  async onUploadImage() {
    try {
      const res = await wx.chooseImage({
        count: 9,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
      });

      // 读取图片文件并转换为base64用于预览和后续提交
      const imagePromises = res.tempFilePaths.map(async (tempFilePath) => {
        try {
          const fileData = await new Promise<string>((resolve, reject) => {
            wx.getFileSystemManager().readFile({
              filePath: tempFilePath,
              encoding: 'base64',
              success: (res) => resolve(res.data as string),
              fail: reject,
            });
          });
          return `data:image/jpeg;base64,${fileData}`;
        } catch (error) {
          console.error('读取图片失败:', error);
          return null;
        }
      });

      const base64Images = (await Promise.all(imagePromises)).filter(Boolean) as string[];
      
      // 更新图片列表（显示预览）
      const images = this.data.formData.images.concat(base64Images);
      this.setData({
        'formData.images': images.slice(0, 9), // 最多9张图片
      });

      wx.showToast({
        title: `添加了 ${base64Images.length} 张图片`,
        icon: 'success',
      });

    } catch (error) {
      console.error('选择图片失败:', error);
      wx.showToast({
        title: '选择图片失败',
        icon: 'none',
      });
    }
  },

  // 删除图片
  onRemoveImage(e: any) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.formData.images];
    images.splice(index, 1);
    this.setData({
      'formData.images': images,
    });
  },

  // 预览图片
  onPreviewImage(e: any) {
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.formData.images[index],
      urls: this.data.formData.images,
    });
  },

  // 提交表单
  async onSubmit() {
    // 检查登录状态
    if (!requireAuth()) {
      return;
    }

    if (!this.validateForm()) {
      return;
    }

    this.setData({ loading: true });

    try {
      const travelData = {
        ...this.data.formData,
        images: this.data.formData.images,
      };

      const result: any = await travelApi.create(travelData);

      // 检查是否是401错误
      if (result && result.detail === '身份认证信息未提供。') {
        // token过期，跳转到登录页
        wx.navigateTo({
          url: '/pages/login/index',
        });
        return;
      }

      wx.showToast({
        title: '创建成功',
        icon: 'success',
        duration: 2000,
      });

      setTimeout(() => {
        wx.navigateBack();
      }, 2000);

    } catch (error: any) {
      console.error('创建旅游记录失败:', error);
      
      // 检查是否是认证错误
      if (error.detail === '身份认证信息未提供。') {
        wx.navigateTo({
          url: '/pages/login/index',
        });
      } else {
        wx.showToast({
          title: error.message || '创建失败',
          icon: 'none',
        });
      }
    } finally {
      this.setData({ loading: false });
    }
  },

  // 表单验证
  validateForm(): boolean {
    const { title, location, start_date, end_date } = this.data.formData;

    if (!title.trim()) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none',
      });
      return false;
    }

    if (!location.trim()) {
      wx.showToast({
        title: '请选择位置',
        icon: 'none',
      });
      return false;
    }

    if (!start_date) {
      wx.showToast({
        title: '请选择开始日期',
        icon: 'none',
      });
      return false;
    }

    if (!end_date) {
      wx.showToast({
        title: '请选择结束日期',
        icon: 'none',
      });
      return false;
    }

    // 验证结束日期不早于开始日期
    if (new Date(end_date) < new Date(start_date)) {
      wx.showToast({
        title: '结束日期不能早于开始日期',
        icon: 'none',
      });
      return false;
    }

    return true;
  },
});
